package com.ititer.web.cookie;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.ititer.model.Account;

public class Cookier {
	private static final Log log = LogFactory.getLog(Cookier.class);
	private static final String domain = "ititer.com";
	private static final int maxage = 700 * 24 * 60 * 60;
	private static final String path = "/";
	public static final String MAIN_COOKIE_NAME = "ITR_SESS";
	public static final String PUB_COOKIE_NAME = "ITR_PUB";

	public static final String ID = "Id";
	public static final String USERNAME = "Username";
	public static final String ACCOUNT_TYPE = "AccountType";
	public static final String ACCOUNT_STATUS = "AccountStatus";
	public static final String NICK_NAME = "Nickname";
	public static final String IP = "Ip";
	public static final String TIME = "Time";
	public static final String LAST_LOGIN_TIME = "LastLoginTime";
	public static final String SEQ_ID = "SeqId";
	public static final String UTF8 = "UTF-8";

	/**
	 * 
	 * @param response
	 * @param account
	 */
	public static void createCookie(HttpServletResponse response, Account account) {
		String id = String.valueOf(account.getId());
		String username = account.getEmail();
		String status = account.getStatus();
		long lastLoginTime = account.getLastLoginTime().getTime();
		createCookie(response, id, username, status, lastLoginTime);
	}

	private static void createCookie(HttpServletResponse response, String id, String username, String accountStatus,
			long lastLoginTime) {

		StringBuffer cookieValue = new StringBuffer();
		cookieValue.append(ID).append("=").append(id).append("&");
		cookieValue.append(USERNAME).append("=").append(username).append("&");
		cookieValue.append(ACCOUNT_STATUS).append("=").append(accountStatus).append("&");
		cookieValue.append(TIME).append("=").append(System.currentTimeMillis()).append("&");
		cookieValue.append(LAST_LOGIN_TIME).append("=").append(lastLoginTime).append("&");

		log.info("Creating cookie :" + MAIN_COOKIE_NAME + " :" + cookieValue);

		//		String encrypVl = DESedeEncryptor.encrypt(cookieValue.toString());
		Cookie cookie = new Cookie(MAIN_COOKIE_NAME, cookieValue.toString());
		cookie.setDomain(domain);
		cookie.setMaxAge(maxage);
		cookie.setPath(path);
		response.addCookie(cookie);
	}

	public static void removeCookie(HttpServletRequest request, HttpServletResponse response) {
		Cookie cl = new Cookie(MAIN_COOKIE_NAME, "");
		cl.setMaxAge(0);
		cl.setPath("/");
		cl.setDomain(domain);
		response.addCookie(cl);
	}
}
